<template>
    <div class="page">
        <h2 class="title">新增通用合同</h2>

        <!-- 表单区域 -->
        <div class="form-container">
            <form @submit.prevent="() => submit('approval')">
                <!-- 两列布局 -->
                <div class="form-grid">
                    <!-- 左列 -->
                    <div class="form-column">
                        <!-- 合同编号 -->
                        <div class="form-item required">
                            <label>*合同编号:</label>
                            <input type="text" v-model="form.contractNumber" placeholder="自动生成合同编号" readonly
                                style="background-color: #f5f5f5;" />
                        </div>

                        <!-- 合同标题 -->
                        <div class="form-item required">
                            <label>*合同标题:</label>
                            <input type="text" v-model="form.contractTitle" placeholder="请输入合同标题" required />
                        </div>
                        <!-- 合同类别 -->
                        <div class="form-item required">
                            <label>*合同类别:</label>
                            <input type="text" v-model="form.contractCategory" placeholder="请输入合同类别" required />
                        </div>


                        <!-- 签订时间 -->
                        <div class="form-item required">
                            <label>*签订时间:</label>
                            <input type="date" v-model="form.signingDate" placeholder="请选择签订时间" required />
                        </div>

                        <!-- 合同金额 -->
                        <div class="form-item">
                            <label>合同金额:</label>
                            <input type="number" v-model="form.contractAmount" placeholder="请输入合同金额" step="0.01" />
                        </div>
                    </div>

                    <!-- 右列 -->
                    <div class="form-column">
                        <!-- 对方单位（下拉，选择后联动负责人） -->
                        <div class="form-item required">
                            <label>*对方单位:</label>
                            <select v-model.number="form.unitId" @change="onUnitChange">
                                <option value="">请选择对方单位</option>
                                <option v-for="u in unitOptions" :key="u.id" :value="u.id">{{ u.name }}</option>
                            </select>
                        </div>

                        <!-- 对方负责人（下拉） -->
                        <div class="form-item required">
                            <label>*对方负责人:</label>
                            <select v-model.number="form.ownerName">
                                <option value="">请选择对方负责人</option>
                                <option v-for="o in ownerOptions" :key="o.id" :value="o.id">{{ o.name }}</option>
                            </select>
                            <div v-if="ownerLoading" style="font-size:12px;color:#888;margin-top:6px">加载负责人...</div>
                        </div>

                        <!-- 经办人 -->
                        <div class="form-item required">
                            <label>*经办人:</label>
                            <input type="text" v-model="form.handler" placeholder="请输入经办人" required />
                        </div>
                    </div>
                </div>

                <!-- 文本区域 -->
                <div class="form-section">
                    <!-- 合同标的或项目说明 -->
                    <div class="form-item">
                        <label>合同标的或项目说明:</label>
                        <textarea v-model="form.contractSubjectDescription" placeholder="请输入合同标的或项目说明"
                            rows="4"></textarea>
                    </div>

                    <!-- 合同主要条款/变更条款 -->
                    <div class="form-item">
                        <label>合同主要条款/变更条款:</label>
                        <textarea v-model="form.contractTerms" placeholder="请输入合同主要条款/变更条款" rows="4"></textarea>
                    </div>
                </div>

                <!-- 文件上传区域 -->
                <div class="form-item">
                    <label>合同文本（附件）:</label>
                    <div class="file-upload">
                        <input ref="fileInput" type="file" multiple @change="onFileChange" />
                        <div class="file-info">已上传:
                            <span v-if="form.contractAttachments && form.contractAttachments.length">
                                <span v-for="(a, i) in form.contractAttachments" :key="i">
                                    <a :href="a" target="_blank">{{ getFileName(a) }}</a><span
                                        v-if="i < form.contractAttachments.length - 1">, </span>
                                </span>
                            </span>
                            <span v-else>未上传</span>
                        </div>
                    </div>
                    <div class="file-tip">(单个附件最大支持20M，支持: PDF、Word、Excel、Txt格式，可多选)</div>
                </div>

                <!-- 按钮区域 -->
                <div class="form-actions">
                    <button type="button" class="btn primary" :disabled="uploadingFile" @click="submit('approval')">
                        提交审批
                    </button>
                    <button type="button" class="btn" :disabled="uploadingFile" @click="cancel">
                        取消
                    </button>
                    <button type="button" class="btn primary" :disabled="uploadingFile" @click="submit('draft')">
                        保存草稿
                    </button>
                </div>
            </form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { uploadFile } from '@/utils/fileUpload'
import { read, write } from '@/assets/Axios/axiosHttple'

const router = useRouter()
const counts = useCounterStore()

// 表单数据模型
const form = reactive({
    id: 0,
    contractNumber: '',
    contractTitle: '',
    unitId: 0,
    ownerName: 0,
    // 可选的货主ID，用于联查货主管理并填充对方单位/负责人
    cargoOwnerId: 0,
    counterpartyUnit: '', // 对方单位
    contractCategory: '',
    signingDate: '',
    handler: '',
    contractAmount: 0,
    contractSubjectDescription: '',
    contractTerms: '',
    contractAttachments: [] as string[], // 合同附件列表
    createDate: '',
    processDetail: 0,
    createdAt: '',
    createdBy: '',
    approver: ''
})

// 文件上传相关 (与其他合同页面一致，上传到七牛云文件服务)
const fileInput = ref<HTMLInputElement>()
const selectedFile = ref<File | null>(null)
const attachmentName = ref('')
const uploadingFile = ref(false)

// 对方单位与负责人下拉选项（用于与货主管理联查后填充）
const counterpartyOptions = ref<Option[]>([])
const ownerOptions = ref<Option[]>([])
const ownerLoading = ref(false)

// 承运/单位下拉的通用类型及数据（与 CarriageContracts 保持一致）
type Option = { id: number; name: string; normalized?: string }
const unitOptions = ref<Option[]>([])

// 加载单位下拉（调用 External 接口，和承运合同页一致）
async function loadUnits() {
    try {
        const res = await read.get('baseinforead/api/External/GetExternalList', { params: { PageIndex: 1, PageSize: 999 } })
        const j: any = res?.data ?? {}
        const dataBlock = j?.data || j
        const list = Array.isArray(dataBlock) ? dataBlock : (Array.isArray(dataBlock?.data) ? dataBlock.data : [])

        unitOptions.value = list.map((x: any) => {
            const name = x.UnitName ?? x.unitName ?? x.Name ?? x.name ?? x.CompanyName ?? x.companyName ?? ''
            const normalized = String(name || '').replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase()
            return { id: Number(x.Id ?? x.id ?? x.UnitId ?? x.unitId), name, normalized }
        }).filter((x: any) => Number.isFinite(x.id) && x.name)
    } catch (error) {
        // ignore
    }
}

// 选择单位后联动加载货主（负责人）
async function onUnitChange() {
    // 切换单位时，先清空负责人候选并显示加载状态
    ownerOptions.value = []
    form.ownerName = 0
    if (form.unitId && Number.isFinite(form.unitId)) {
        const selectedUnit = unitOptions.value.find(u => u.id === Number(form.unitId))
        if (selectedUnit && selectedUnit.name) form.counterpartyUnit = selectedUnit.name
        ownerLoading.value = true
        try {
            await fetchCargoOwnerByUnitId(Number(form.unitId))
        } finally {
            ownerLoading.value = false
        }
    } else {
        ownerOptions.value = []
        form.ownerName = 0
    }
}

// 根据单位ID在货主列表中查找对应负责人（复用承运合同的逻辑）
async function fetchCargoOwnerByUnitId(unitId: number) {
    // 使用与承运合同相同的宽松匹配逻辑：优先按单位ID匹配，ID无匹配则按单位名称normalized回退匹配
    try {
        const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params: { PageIndex: 1, PageSize: 999 } })
        const j: any = res?.data ?? {}
        const dataBlock = j?.data || j
        const list = Array.isArray(dataBlock) ? dataBlock : (Array.isArray(dataBlock?.data) ? dataBlock.data : [])

        const toNumber = (v: any) => { const n = Number(v); return Number.isFinite(n) ? n : NaN }

        // 按单位ID精确匹配
        let matchedCargoOwners = list.filter((item: any) => {
            const itemUnitId = toNumber(item.UnitId ?? item.unitId ?? item.Id ?? item.id)
            return !Number.isNaN(itemUnitId) && itemUnitId === unitId
        })

        // 按单位名称回退匹配（normalized）
        if (matchedCargoOwners.length === 0) {
            const selectedUnit = unitOptions.value.find(u => u.id === unitId)
            const unitNormalized = selectedUnit?.normalized || selectedUnit?.name?.replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase()
            if (unitNormalized) {
                matchedCargoOwners = list.filter((item: any) => {
                    const names = [item.UnitName, item.unitName, item.CompanyName, item.companyName, item.Name, item.name]
                    return names.some((n: any) => typeof n === 'string' && n.replace(/\s+/g, '').replace(/[\-_,.·•()（）]/g, '').toLowerCase().includes(unitNormalized))
                })
            }
        }

        console.debug('[General fetchCargoOwnerByUnitId] unitId=', unitId, 'matchedCount=', matchedCargoOwners.length)

        if (matchedCargoOwners.length > 0) {
            const ownerNames = matchedCargoOwners.map((item: any) => {
                return item.ownerName ?? item.OwnerName ?? item.Contact ?? item.contact ?? item.Principal ?? item.principal ?? item.Name ?? item.name
            }).filter(Boolean) as string[]

            if (ownerNames.length > 0) {
                // 构造 id/name 对，优先使用记录中的 OwnerId/Id 字段作为 id
                const pairs: Array<{ id: number | null; name: string }> = matchedCargoOwners.map((item: any) => {
                    const id = Number(item.OwnerId ?? item.ownerId ?? item.Id ?? item.id)
                    const name = String(item.ownerName ?? item.OwnerName ?? item.Contact ?? item.contact ?? item.Principal ?? item.principal ?? item.Name ?? item.name ?? '')
                    return { id: Number.isFinite(id) ? id : null, name }
                }).filter((p: { id: number | null; name: string }) => Boolean(p.name))

                const unique: Option[] = []
                const seen = new Set<string | number>()
                let fallbackId = -1
                for (const p of pairs) {
                    const key = p.id ?? p.name
                    if (seen.has(key)) continue
                    seen.add(key)
                    const useId = p.id ?? (fallbackId--)
                    unique.push({ id: useId as number, name: p.name })
                }

                ownerOptions.value = unique
                if (ownerOptions.value.length === 1) form.ownerName = ownerOptions.value[0].id
                else form.ownerName = 0
            } else {
                ownerOptions.value = []
                form.ownerName = 0
            }
        } else {
            ownerOptions.value = []
            form.ownerName = 0
        }
    } catch (error) {
        console.error('[General fetchCargoOwnerByUnitId] error', error)
        ownerOptions.value = []
        form.ownerName = 0
    }
}

// 自动生成合同编号（格式：TY+YYYYMMDDHHMMSS）
function generateContractNumber() {
    const pad = (n: number) => n.toString().padStart(2, '0')
    const d = new Date()
    const yyyy = d.getFullYear()
    const mm = pad(d.getMonth() + 1)
    const dd = pad(d.getDate())
    const hh = pad(d.getHours())
    const mi = pad(d.getMinutes())
    const ss = pad(d.getSeconds())
    return `TY${yyyy}${mm}${dd}${hh}${mi}${ss}`
}



// 从 URL 或路径中提取文件名
function getFileName(urlOrPath: string) {
    try {
        const u = new URL(urlOrPath)
        const segs = (u.pathname || '').split('/')
        return decodeURIComponent(segs[segs.length - 1] || urlOrPath)
    } catch {
        const segs = String(urlOrPath).split(/[\\/\\\\]/)
        return segs[segs.length - 1] || String(urlOrPath)
    }
}

// 多文件上传到后端 FileUpload
async function onFileChange(e: Event) {
    const input = e.target as HTMLInputElement
    const files = input?.files
    if (!files || files.length === 0) return
    uploadingFile.value = true
    try {
        for (let i = 0; i < files.length; i++) {
            const f = files[i]
            try {
                const url = await uploadFile(f)
                if (url) form.contractAttachments.push(url)
                else form.contractAttachments.push(f.name)
            } catch (err: any) {
                console.error('上传失败', err)
                // 不阻塞：使用文件名占位并继续
                form.contractAttachments.push(f.name)
            }
        }
    } catch (err: any) {
        console.error('处理文件时出错', err)
        alert(err?.message || '文件处理失败')
    } finally {
        uploadingFile.value = false
        if (fileInput.value) fileInput.value.value = ''
    }
}
// 表单验证
function validate() {
    if (!form.contractTitle.trim()) {
        alert('请输入合同标题')
        return false
    }
    if (typeof form.ownerName === 'number') {
        if (!form.ownerName || Number(form.ownerName) === 0) { alert('请输入对方负责人'); return false }
    } else {
        if (!String(form.ownerName).trim()) { alert('请输入对方负责人'); return false }
    }
    if (!form.signingDate) {
        alert('请选择签订时间')
        return false
    }
    if (!form.counterpartyUnit.trim()) {
        alert('请输入对方单位')
        return false
    }
    if (!form.contractCategory.trim()) {
        alert('请输入合同类别')
        return false
    }
    if (!form.handler.trim()) {
        alert('请输入经办人')
        return false
    }
    return true
}

// 提交表单
async function submit(mode: 'approval' | 'draft') {
    if (!validate()) return
    if (uploadingFile.value) { alert('文件正在上传，请等待上传完成再提交'); return }
    // 附件功能已移除，跳过相关校验

    try {
        // 准备提交数据（同时提供 ownerId 与 ownerName，兼容后端不同字段期望）
        const resolvedOwnerId = (typeof form.ownerName === 'number' && Number(form.ownerName) > 0) ? Number(form.ownerName) : undefined
        const resolvedOwnerName = (resolvedOwnerId ? (ownerOptions.value.find(o => o.id === resolvedOwnerId)?.name || '') : (typeof form.ownerName === 'string' ? String(form.ownerName) : ''))
        const submitData = {
            id: 0,
            contractNumber: form.contractNumber,
            contractTitle: form.contractTitle,
            unitId: form.unitId,
            unitName: form.counterpartyUnit,
            ownerId: resolvedOwnerId ?? 0,
            ownerName: resolvedOwnerName || String(form.ownerName || ''),
            contractCategory: form.contractCategory,
            signingDate: form.signingDate ? new Date(form.signingDate).toISOString() : new Date().toISOString(),
            handler: form.handler,
            contractAmount: Number(form.contractAmount) || 0,
            contractSubjectDescription: form.contractSubjectDescription,
            contractTerms: form.contractTerms,
            // 附件字段
            contractAttachments: form.contractAttachments || [],
            contractAttachment: Array.isArray(form.contractAttachments) ? form.contractAttachments.join(',') : (form.contractAttachments || ''),
            createDate: new Date().toISOString(),
            processDetail: mode === 'approval' ? 1 : 0, // 提交审批为1，保存草稿为0
            createdAt: new Date().toISOString(),
            // 后端要求 createdBy 为字符串，强制转换为 string
            createdBy: String(form.createdBy ?? counts.Logins.UserId ?? counts.Logins.Account ?? counts.Logins.Nickname ?? ''),
            approver: mode === 'approval' ? (form.approver || counts.Logins.Nickname || counts.Logins.Account || '') : (form.approver || ''),
            // 一些后端接口需要 command 字段指示操作类型（避免 validation error: command is required）
            command: mode === 'approval' ? 'submit' : 'draft'
        }
        // 打印请求体便于后端调试
        console.debug('[AddGeneral submit] submitData=', submitData)

        const candidates = [
            'contractmanagementwrite/api/ContractManagement/CreateGeneral/general/create',
            'contractmanagementwrite/api/ContractManagement/Create/create',
            'contractmanagementwrite/api/ContractManagement/Create'
        ]
        let lastErr: any = null
        for (const u of candidates) {
            try {
                const res = await write.post(u, submitData)
                const result: any = res?.data ?? {}
                if (res.status === 200 && Number(result?.code) === 200) {
                    const message = mode === 'approval' ? '提交审批成功' : '保存草稿成功'
                    alert(message)
                    router.push('/GetGeneralContracts?refresh=1')
                    return
                }
                lastErr = { status: res?.status, body: result }
            } catch (e) { lastErr = e }
        }
        const result = lastErr?.body || {}
        console.error('[AddGeneral submit] server response:', result)
        let errMsg = ''
        if (result?.errors && typeof result.errors === 'object') {
            const parts: string[] = []
            for (const k of Object.keys(result.errors)) {
                const v = result.errors[k]
                if (Array.isArray(v)) parts.push(`${k}: ${v.join('; ')}`)
                else parts.push(`${k}: ${String(v)}`)
            }
            errMsg = parts.join('\n')
        } else if (result?.message) {
            errMsg = String(result.message)
        } else {
            errMsg = '操作失败'
        }
        alert(errMsg)
    } catch (error) {
        console.error('提交失败:', error)
        alert('提交失败，请重试')
    }
}

// 取消操作
function cancel() {
    router.push('/GetGeneralContracts')
}

// 组件挂载时初始化
onMounted(async () => {
    // 自动生成合同编号
    form.contractNumber = generateContractNumber()

    // 并行加载单位下拉（External）以便下拉有数据
    await loadUnits()

    // 设置经办人为当前登录用户（从 pinia store 中读取登录信息）
    form.handler = counts.Logins.Nickname || counts.Logins.Account || ''
    form.createdBy = counts.Logins.UserId || counts.Logins.Account || counts.Logins.Nickname || ''

    // 设置默认签订时间为今天
    const today = new Date().toISOString().split('T')[0]
    form.signingDate = today

    // 如果 URL 中包含 cargoOwnerId 参数，则自动联查并填充对方单位/负责人
    try {
        const url = new URL(window.location.href)
        const coid = url.searchParams.get('cargoOwnerId') || url.searchParams.get('cargoownerid')
        if (coid) {
            const n = Number(coid)
            if (!Number.isNaN(n) && n > 0) fetchCargoOwnerById(n)
        }
    } catch (e) { /* ignore */ }
})

// 通过货主ID从后端获取货主信息并填充对方单位与负责人
async function fetchCargoOwnerById(id: number) {
    try {
        const res = await read.get(`baseinforead/api/CargoOwner/GetCargoOwnerById/${encodeURIComponent(String(id))}`)
        const d = res?.data?.data ?? res?.data
        if (!d) return

        form.cargoOwnerId = id
        const unitName = d.UnitName ?? d.unitName ?? d.CompanyName ?? d.companyName ?? d.Name ?? d.name
        const ownerName = d.OwnerName ?? d.ownerName ?? d.Contact ?? d.contact ?? d.Principal ?? d.principal
        if (unitName) {
            counterpartyOptions.value = [{ id: id, name: unitName }]
            form.counterpartyUnit = unitName
        }
        if (ownerName) {
            ownerOptions.value = [{ id: id, name: ownerName }]
            form.ownerName = id
        }
    } catch (e) {
        console.error('[fetchCargoOwnerById] error', e)
    }
}

// promptAndFetchCargoOwner 已移除，保留 fetchCargoOwnerById 供外部调用（例如通过 URL 参数）
</script>

<style scoped>
.page {
    padding: 16px;
    max-width: 1200px;
    margin: 0 auto;
}

.title {
    margin: 8px 0 20px;
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.form-container {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-bottom: 24px;
}

.form-column {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.form-section {
    margin-bottom: 24px;
}

.form-item {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.form-item.required label::before {
    content: '*';
    color: #ff4d4f;
    margin-right: 4px;
}

.form-item label {
    font-weight: 500;
    color: #333;
    font-size: 14px;
}

.form-item input,
.form-item textarea,
.form-item select {
    padding: 8px 12px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    font-size: 14px;
    transition: border-color 0.3s;
}

.form-item input:focus,
.form-item textarea:focus,
.form-item select:focus {
    outline: none;
    border-color: #1677ff;
    box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.2);
}

.form-item textarea {
    resize: vertical;
    min-height: 80px;
}

.file-upload {
    display: flex;
    align-items: center;
    gap: 12px;
}

.file-info {
    color: #666;
    font-size: 14px;
}

.file-tip {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
}

.form-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #f0f0f0;
}

.btn {
    padding: 8px 24px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    background: #fff;
    color: #333;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
}

.btn:hover {
    border-color: #1677ff;
    color: #1677ff;
}

.btn.primary {
    background: #1677ff;
    color: #fff;
    border-color: #1677ff;
}

.btn.primary:hover {
    background: #4096ff;
    border-color: #4096ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .form-actions {
        flex-direction: column;
    }

    .btn {
        width: 100%;
    }
}
</style>
